package authentication.token;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * <h4>登录</h4>
 * 约定登录时使用AES加密和解密
 *
 * 登录时需要登录方将 url + timestamp + 随机字符串使用MD5加密得到加密串。
 * 然后登录控制器验证登录是否成功，成功则从加密串中取第7位到第15位（subString(7,23)）字符串作为AES加密的key,
 * 将token加密和返回给客户端，客户端通过key来解密得到token。
 *
 * @author yuqi<307530884@qq.com> <2017/3/28>
 * @version 1.0
 * @since 1.0
 */
public class SignUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SignUtil.class);

    public static String setLoginSign(Request request){
        String timestamp = String.valueOf(System.currentTimeMillis());
        String url = request.get(Request.url);

        String nonce = "helloWorld";
        String signStr = url + timestamp + nonce;
        String md5Str = DigestUtils.md5Hex(signStr);

        request.put("nonce", nonce);
        request.put("timestamp", timestamp);
        request.put("sign", md5Str);


        String key = getAesKey(md5Str);
        return key;
    }

    private static String getAesKey(String md5Str){
        String key = md5Str.substring(7, 23);
//        key = Base64.encodeBase64String(key.getBytes());
        return key;
    }

    public static String checkLoginSignAndGetKey(Request request){
        String timestamp = request.get("timestamp");
        String url = request.get(Request.url);
        String nonce = request.get("nonce");
        String sign = request.get("sign");

        if(sign == null || "".equals(sign)){
            throw new IllegalArgumentException("no sign");
        }

        String signStr = url + timestamp + nonce;
        String md5Str = DigestUtils.md5Hex(signStr);

        if(!sign.equals(md5Str)){
            LOGGER.error("sign:{},signStr:{},md5Str:{}", sign, signStr, md5Str);
            throw new IllegalArgumentException("sign valid error");
        }

        String aesKey = getAesKey(md5Str);
        return aesKey;
    }

    public static String createLoginSuccessToken(String aseKey){
        String trueToken = DigestUtils.md2Hex("123abc");

        String aseToken = AES.encrypt(trueToken, aseKey);

        LOGGER.debug("trueToken:{},aesToken:{}", trueToken, aseToken);

        return aseToken;
    }

    public static String getToken(Response response, String key){
        LOGGER.info("key=[{},{}]", key, key.length());

        String token = response.get("token");

        if(token != null && !"".equals(token)){
            token = AES.decrypt(token, key);
        }
        return token;
    }

}
